import { useEffect, useMemo, useState } from 'react';
import { EyeOutlined } from '@ant-design/icons';
import { UploadFormCommon } from '@/components/UploadForm';
import { TagSelectNew as TagSelect } from '@/components/TagSelectNew';
import { splitFileUrl, downloadTemplate, getFileNameNotType, getUserDepID } from '@/utils';
import { useDescriptionsType } from '@/components/DescriptionsType';
import moment from 'moment';
import { Tooltip, TreeSelect, message, Button } from 'antd';
import { UpdateMaterielView } from './UpdateMaterielView';
import MyIcon from '@/components/MyIcon';
import { getBaseUrl } from '@/services/urlconst';
import { getCompanyTreeNodeListSev, getFlowOrgTreeByOrgIDService, readReadShowFileService } from '@/services/BaseLayout';
import { handleNotPostion } from '@/pages/ContractController/ContractManage/mconfig';

const getUpdateConfig = ({ acceptForm, pageType, record, openMaterialModalStatus, storageList, changeOriginalStore, changeNewStore, openProperty }) => {
  /**  获取数据字典 */
  // const { loadMapInfo, mapLoading } = getLoadMapList([
  //   `${getTenantID()}${ILoadMapTypeAll.ASSET_TYPE}`, //资产类型
  //   `${getTenantID()}${ILoadMapTypeAll.MATERIAL_BRAND}`, //材料品牌
  // ]);

  // 获取组织机构树接口
  const { getFlowOrgTreeRun, getFlowOrgTreeLoading, getFlowOrgList } = getFlowOrgTreeByOrgIDService();

  // 获取最大组织结构树
  const { companyTreeNodeListRun, companyTreeNodeListLoading, companyTreeNodeList } = getCompanyTreeNodeListSev();

  // 默认请求
  useEffect(() => {
    /** 初始化请求组织机构 */
    let payload = {
      params: '0',
      flowType: '0',
    };
    getFlowOrgTreeRun(payload);
    companyTreeNodeListRun();
  }, []);

  /** 轻阅读预览 */
  const { readReadShowFileRun } = readReadShowFileService();

  /**轻阅读预览 */
  const onOpenReadOfdWord = (fieldUrl: string) => {
    readReadShowFileRun({ fieldPath: `${getBaseUrl()}${fieldUrl}` });
  };

  /** 是否跨单位state 1=单位内 2=跨单位*/
  const [isTransferType, setTransferType] = useState<string | number>(1);

  useEffect(() => {
    // 回填表单
    acceptForm?.setFieldsValue({
      ...record,
      createTime: moment(record?.createTime),
    });
    if (record?.transferType) {
      setTransferType(record?.transferType);
    }
  }, [record, storageList]);

  const YJNodeTreeData = useMemo(() => {
    if (isTransferType && getFlowOrgList && companyTreeNodeList) {
      if (isTransferType == '1' && getFlowOrgList?.length) {
        return handleNotPostion(getFlowOrgList);
      } else if (isTransferType == '2' && companyTreeNodeList) {
        return handleNotPostion(companyTreeNodeList);
      } else {
        return [];
      }
    }
  }, [getFlowOrgList?.length, companyTreeNodeList?.length, isTransferType]);

  const disabled: boolean = pageType === 'detail';

  /** 表单配置 */
  const [config, methods] = useDescriptionsType({
    labelWidth: 190,
    basicForm: acceptForm,
    name: 'accept-addAndEdit',
    schemas: [
      {
        key: 'accept-basic',
        title: '',
        fieldChildren: [
          {
            label: '申请日期',
            field: 'createTime',
            component: 'DatePicker',
            placeholder: '请选择申请日期',
            disabled: disabled,
            required: true,
            disabledDate: (current) => {
              return current && current > moment(new Date(), 'YYYY-MM-DD');
            },
          },
          {
            field: `applyCode`,
            label: `流水单号`,
            component: 'Input',
            disabled: true,
            placeholder: '自动带出',
            required: false,
          },
          {
            field: `createrName`,
            label: `申请人`,
            component: 'Input',
            disabled: true,
            required: false,
            placeholder: '自动带出',
          },
          {
            field: `createPhone`,
            label: `联系电话`,
            component: 'Input',
            disabled: true,
            required: false,
            placeholder: '自动带出',
          },
          {
            field: `createDepartmentName`,
            label: `申请部门/单位`,
            component: 'Input',
            disabled: true,
            required: false,
            placeholder: '自动带出',
          },
          {
            field: `createPositionName`,
            label: `职务岗位`,
            component: 'Input',
            disabled: true,
            required: false,
            placeholder: '自动带出',
          },
          {
            field: `applyTitle`,
            label: `事项名称`,
            component: 'Input',
            disabled: disabled,
            placeholder: '请填写',
            required: true,
            colSpan: 0,
          },
          {
            field: `transferType`,
            label: `是否跨单位`,
            component: 'Render',
            required: true,
            disabled: disabled,
            placeholder: '请选择',
            colSpan: 2,
            render: (text) => {
              return (
                <TagSelect
                  colSpan={24}
                  formLabel={''}
                  formName={'transferType'}
                  defalultKeys={Number(text)}
                  onChange={(val) => setTransferType(val)}
                  radioDisabled={disabled}
                  radioList={[
                    {
                      value: 1,
                      name: '单位内',
                    },
                    {
                      value: 2,
                      name: '跨单位',
                    },
                  ]}
                />
              );
            },
          },
          {
            field: `originalStoreDepartmentID`, // originalStoreID => originalStoreDepartmentID [2024/07/15]
            label: `移交部门`,
            component: 'Render',
            disabled: disabled,
            required: true,
            placeholder: '请选择',
            message: '请选择',
            render: (text) => {
              if (pageType === 'detail') {
                return <span>{record.originalStoreDepartmentName || '--'}</span>; // originalStoreName => originalStoreDepartmentName [2024/07/15]
              } else {
                return (
                  <TreeSelect
                    onChange={(_v, _n, extra: Record<string, any>) => changeOriginalStore(extra?.triggerNode?.props?.attributes?.companyID || '')}
                    // treeData={storageList.filter((v) => v.storeUserID != getUserID())}
                    treeData={YJNodeTreeData}
                    loading={getFlowOrgTreeLoading || companyTreeNodeListLoading}
                    disabled={disabled}
                    placeholder="请选择移交部门"
                    fieldNames={{
                      label: 'title',
                      value: 'id',
                      children: 'children',
                    }}
                    showSearch={true}
                  />
                );
              }
            },
          },
          {
            field: `newStoreDepartmentID`, // newStoreID => newStoreDepartmentID [2024/07/15]
            label: `接收部门`,
            component: 'Render',
            disabled: disabled,
            required: true,
            placeholder: '请选择',
            message: '请选择',
            render: (text) => {
              if (pageType === 'detail') {
                return <span>{record.newStoreDepartmentName || '--'}</span>; // newStoreName => newStoreDepartmentName [2024/07/15]
              } else {
                return (
                  <TreeSelect
                    onChange={(_v, _n, extra: Record<string, any>) => changeNewStore(extra?.triggerNode?.props?.attributes?.companyID || '')}
                    // treeData={storageList.filter((v) => v.storeUserID == getUserID())}
                    treeData={handleNotPostion(getFlowOrgList)}
                    loading={getFlowOrgTreeLoading}
                    disabled={disabled}
                    placeholder="请选择接收部门"
                    fieldNames={{
                      label: 'title',
                      value: 'id',
                      children: 'children',
                    }}
                    showSearch={true}
                  />
                );
              }
            },
          },
          {
            field: `applyInfo`,
            label: `调剂说明`,
            component: 'InputTextArea',
            disabled: disabled,
            placeholder: '请填写',
            required: true,
            colSpan: 2,
            allowClear: true,
            showCount: true,
            maxLength: 200,
            autoSize: { minRows: 2, maxRows: 4 },
          },
          {
            field: `applyFile`,
            label: `相关附件`,
            component: 'Render',
            required: false,
            placeholder: '请上传',
            colSpan: 2,
            render: (text, record) => {
              const fileName = 'applyFile';
              return (
                <>
                  {!disabled ? (
                    <UploadFormCommon
                      form={acceptForm}
                      fileFormName={fileName}
                      spanCol={24}
                      inRowProportion={24}
                      name={'attachFile'}
                      required={false}
                      // accept={'.doc|.docx'}
                      url={'/assetInfo/uploadFile'}
                      downloadUrl={'/assetInfo/downloadFile'}
                      fileFormDelName={'delFile'}
                      delFunc={(delFilePath: string) => {
                        console.log('--- w文件url', delFilePath);
                      }}
                      // maxFile={1}
                      defaultFiles={text}
                      hintTitle={'且只能上传 1 个！'}
                      fieldBusiPath={'assetFile'}
                      // isShowUploadBtn={true}
                    >
                      上传
                    </UploadFormCommon>
                  ) : (
                    <div
                      style={{
                        height: '100%',
                        display: 'flex',
                        alignItems: 'center',
                        marginLeft: '8px',
                      }}
                    >
                      {record?.[fileName]
                        ? splitFileUrl(record?.[fileName])?.map((e, i) => {
                            return (
                              <div>
                                <Tooltip title={e.attachName} key={new Date().getTime() * 25615265152 + e?.attachName}>
                                  <a
                                    onClick={() => {
                                      message.success('下载中，请稍后...');
                                      downloadTemplate('/assetInfo/downloadFile', e?.attachName, e?.attachUrl, () => {});
                                    }}
                                  >
                                    <MyIcon type="icon-file-text-fill" />
                                    &nbsp;
                                    {getFileNameNotType(e.attachName, 8)}
                                  </a>
                                </Tooltip>
                                {/* 轻阅读预览 */}
                                <Tooltip title={'在线预览'}>
                                  <Button type="link" size="small" onClick={() => onOpenReadOfdWord(e?.attachUrl)} icon={<EyeOutlined />} />
                                </Tooltip>
                              </div>
                            );
                          })
                        : '--'}
                    </div>
                  )}
                </>
              );
            },
          },
        ],
      },
      {
        key: 'accept-procurement',
        title: '',
        fieldCustomDom: <UpdateMaterielView openMaterialModalStatus={openMaterialModalStatus} pageType={pageType} openProperty={openProperty} />,
      },
    ],
  });

  return {
    config,
    methods,
  };
};

export { getUpdateConfig };
